<?php

class InvoiceEmpController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/customer';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

               'users'=>array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new InvoiceEmp;


        $model->credit = 100;
        if (isset($_POST)) {

            $model->attributes = $_POST;
            $model->status=1;
            if($model->save()){
                echo json_encode(array(
                    'success'=>true,
                    'msg'=>"Saving successful"
                ));
            }else{
                echo json_encode(array(
                    'success'=>false,
                    'errors'=>$model->getErrors()
                ));
            }
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate() {
        

        if (isset($_POST) && isset($_POST['id']) && $_POST['id']!=NULL) {
            //update employee 
            $model = $this->loadModel($_POST['id']);
            if($model==NULL) Yii::app()->end();
            $model->attributes = $_POST;
        
            if($model->save()){
                echo json_encode(array(
                    'success'=>true,
                    'msg'=>"Saving successful"
                ));
            }else{
                echo json_encode(array(
                    'success'=>false,
                    'errors'=>$model->getErrors()
                ));
            }
        }else{
            //insert employee
             $model = new InvoiceEmp;


            $model->credit = 100;
            if (isset($_POST)) {

                $model->attributes = $_POST;
                $model->status=1;
                if($model->save()){
                    echo json_encode(array(
                        'success'=>true,
                        'msg'=>"Saving successful"
                    ));
                }else{
                    echo json_encode(array(
                        'success'=>false,
                        'errors'=>$model->getErrors()
                    ));
                }
            }
        }

    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {

        $model = $this->loadModel($id);
        $invoice = $model->invoice;
        $model->delete();
    
    }

    /**
     * Lists all models.
     */
    public function actionIndex($invoice) {

        $model = Invoice::model()->findByPk($invoice);
        $location = Locations::model()->find('locno=:locno', array('locno' => $model->locno));
        $customer = Customers::model()->find('custno=:custno', array(
            'custno' => $location->custno));
        
        outputJsByList(Employees::model()->getEmployeeList(), 'employee');
        $this->render('index', array('location' => $location,
            'customer' => $customer,
            'model' => $model));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = InvoiceEmp::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    //TODO move this code to model
    public function actionList($invoice, $page=1, $sort=NULL, $dir=NULL) {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;

        $employers = new CActiveDataProvider('InvoiceEmp', array(
                    'criteria' => array(
                        'condition' => "invoice='$invoice'",
                        'order' => $sort != NULL ? $sort . ' ' . $dir : '',
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $empList = array();
        if ($employers->getTotalItemCount() > 0) {
            $empList['totalCount'] = $employers->getTotalItemCount();
            $empList['type'] = 'Items';
            foreach ($employers->getData() as $i=>$item) {
                $empList['data'][$i] = $item->getAttributes();
                if($item->employee!=NULL){
                    $empList['data'][$i]['employeetext']=$item->employee->firstname.' '.$item->employee->lastname;
                }
            }
            echo json_encode($empList);
        }
        Yii::app()->end();
    }

    /**
     * @return JSON with technician data
     */
    public function actionGetTechnicianData($id) {

        $model = Employees::model()->findByPk($id);
        $data = array();
        $data['hrate'] = $model->hrrate;
        $data['overhead'] = $model->overhead;
        echo json_encode($data);
        Yii::app()->end();
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'invoice-emp-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
